<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Description of product
 *
 * @author b4by
 */
class product extends MY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('model_product');
		$this->load->model('model_product_catalogue');
		$this->load->model('model_product_info');
		$this->load->model('model_product_location');
		$this->load->model('model_product_discount');
		$this->load->model('model_product_image');
		$this->load->model('model_file');
		$this->data['errors'] = array();
		$this->load->helper('form');
	}

	public function index() {
		$this->data['temp'] = 'admin/product/index';
		$this->load->view('admin/main', $this->data);
	}

	public function read() {
		$pagination = pagination_init($this->model_product->get_total(), request('p'));

		$products = $this->model_product->get_list($this->siteConfig->lang, array(
			'limit' => array($pagination->from, $pagination->limit),
			'order'	=> array('index','asc')
				));


		foreach ($products as &$product) {
			$product->thumb = image_url($product->thumb);
			$product->edit_link = url_create('admin', 'product', 'update', $product->id);
		}
		echo json_encode(array(
			'state' => 'success',
			'data' => $products,
			'pagination' => $pagination,
		));
	}

	public function create() {
		$this->data['product'] = array();
		if ($this->input->post('submit')) {
			$this->data['product'] = request_filter(array('image_id', 'info', 'images', 'catalogues','index'));
			$this->_valid_form();
			if ($this->form_is_valid()) {
				$image = $this->model_file->get_info($this->input->post('image_id'));
				$data = request_filter(array('image_id','home','index'));
				$data['image'] = $image->file_name;
				$data['thumb'] = $image->thumb_name;
				$data['time'] = now();
				$this->model_file->update($image->id, array(
					'status' => 1,
				));

				$product_id = $this->model_product->create($data);


				// Images
				$images = $this->input->post('images');
				foreach ($images as $image_id) {
					$image = $this->model_file->get_info($image_id);
					$this->model_product_image->create(array(
						'product_id' => $product_id,
						'image_id' => $image->id,
						'path' => $image->file_name,
						'thumb' => $image->thumb_name,
					));
					$this->model_file->update($image->id, array('status' => 1));
				}

				// Info
				$info = request('info');
				foreach ($this->languages as $lang) {
					$info[$lang->id]['product_id'] = $product_id;
					$info[$lang->id]['lang_id'] = $lang->id;
				}
				foreach ($info as $row) {
					$this->model_product_info->create($row);
				}

				// Catalogues
				$catalogues = request('catalogues');

				foreach ($catalogues as $catalogue) {

					$this->model_product_catalogue->create(array(
						'product_id' => $product_id,
						'cat_id' => $catalogue,
					));
				}

				echo json_encode(array(
					'state' => 'success',
					'redirect' => url_create('admin', 'product', 'index')
				));
			} else {
				echo json_encode(array(
					'state' => 'error',
					'errors' => $this->data['errors'],
				));
			}
			exit;
		}
		$this->_init();
		$this->data['method'] = __FUNCTION__;
		$this->data['temp'] = 'admin/product/detail';
		$this->load->view('admin/main', $this->data);
	}

	public function update($id) {
		$product = $this->model_product->get_info($id);
		if ($product === false) {
			show_error(lang('invalid_product'));
		}
		$this->data['product'] = $product;
//		pr($product);die;
		if ($this->input->post('submit')) {
			$this->load->library('form_validation');
			$_POST['id'] = $id;
			$this->_valid_form(TRUE);
			if ($this->form_is_valid()) {
				$data = request_filter(array('image_id','home','index'));
				if ($this->input->post('image_id') != $product->image_id) {
					$img = $this->model_file->get_info($data['image_id']);
					$data['image'] = $img->file_name;
					$data['thumb'] = $img->thumb_name;
				}
				$this->model_product->update($product->id, $data);
				// Info
				$info = request('info');
				foreach ($this->languages as $lang) {
					$info[$lang->id]['product_id'] = $product->id;
					$info[$lang->id]['lang_id'] = $lang->id;
				}
				foreach ($info as $row) {
					if (isset($product->info[$row['lang_id']]))
						$this->model_product_info->update_rule(array(
							'product_id' => $row['product_id'],
							'lang_id' => $row['lang_id'],
								), $row);
					else
						$this->model_product_info->create($row);
				}

				// Catalogues
				$catalogues = request('catalogues');
				foreach ($product->catalogues as $cat)
					if (!in_array($cat, $catalogues))
						$this->model_product_catalogue->del_rule(array(
							'product_id' => $product->id,
							'cat_id' => $cat
						));
				foreach ($catalogues as $catalogue) {
					if (!in_array($catalogue, $product->catalogues))
						$this->model_product_catalogue->create(array(
							'product_id' => $product->id,
							'cat_id' => $catalogue,
						));
				}

				// Images
				$images = $this->input->post('images');
				foreach ($product->images as $image) {
					if (!in_array($image->image_id, $images)) {
						$this->model_product_image->del($image->id);
						$this->model_file->update($image->image_id, array(
							'status' => 0,
						));
					}
				}

				foreach ($images as $image_id) {
					if (!isset($product->images[$image_id])) {
						$image = $this->model_file->get_info($image_id);
						$this->model_product_image->create(array(
							'product_id' => $product->id,
							'image_id' => $image->id,
							'path' => $image->file_name,
							'thumb' => $image->thumb_name,
						));
						$this->model_file->update($image->id, array('status' => 1));
					}
				}
				echo json_encode(array(
					'state' => 'success',
					'message' => lang('product_updated'),
					'redirect' => url_create('admin', 'product', 'index')
				));
			} else {
				echo json_encode(array(
					'state' => 'error',
					'errors' => $this->data['errors']
				));
			}
			exit();
		}
		$this->_init();
		$this->data['method'] = __FUNCTION__;
		$this->data['temp'] = 'admin/product/update';
		$this->load->view('admin/main', $this->data);
	}

	function delete() {
		$id = request('id');
		$product = $this->model_product->get_info($id);
		if(!$product){
			echo json_encode(array(
				'state'=> 'error',
				'message'=> lang('invalid_product')
			));
			exit();
		}
		foreach($product->images as $img)
			$this->model_file->update($img->image_id,array('status'=>0));
		$this->model_product_image->del_rule(array('product_id'=>$id));
		$this->model_product_catalogue->del_rule(array('product_id'=>$id));
		$this->model_product->del($id);
		echo json_encode(array(
			'state' => 'success',
			'id' => $id,
		));
	}

	public function delete_image() {
		$id = request('id');
		$image = $this->model_product_image->get_info($id);
		if ($image === false) {
			echo json_encode(array(
				'state' => 'error',
				'title' => lang('error'),
				'message' => lang('image_not_found')
			));
		} else {
			$this->delImage($image->path);
			$this->delImage($image->thumb);
			$this->model_product_image->del($id);
			echo json_encode(array(
				'state' => 'success',
				'id' => $id
			));
		}
	}

	public function _valid_form($id = false) {
		$this->load->helper('form');
		$this->load->library('form_validation');
		if ($id !== false) {
			$this->form_validation->set_rules('id', 'lang:product', 'callback__check_product_id');
		}
		$this->form_validation->set_rules('image_id', 'lang:product_image', 'callback__check_image');
		$this->form_validation->set_rules('info', 'lang:product_info', 'callback__check_info');
		$this->form_validation->set_rules('images', 'lang:product_images', 'callback__check_images');
		$this->form_validation->set_rules('catalogues', 'lang:product_catalogue', 'callback__check_catalogue');
		return $this->form_is_valid();
	}

	public function _init() {
		$this->load->model('model_catalogue');
		$this->load->model('model_location');
		
		$catalogues = $this->model_catalogue->get_list_hash($this->siteConfig->lang, array(
			'where'	=> array('type'=>1),
			'order' => array('index', 'asc')
				));

//		$locations = $this->model_location->get_list_hash(array(
//			'order' => array('index', 'asc')
//				));
//pr($catalogues);die;
		array_to_object($catalogues);
		
		object_prefix_create($catalogues, '', '&nbsp;&nbsp;&nbsp;&nbsp;');
		$this->data['catalogues'] = array();
		object_to_array($this->data['catalogues'], $catalogues);
		
//		array_to_object($locations);
//		object_prefix_create($locations, '', '&nbsp;&nbsp;&nbsp;&nbsp;');
//		$this->data['locations'] = array();
//		object_to_array($this->data['locations'], $locations);
	}

	public function _check_image($id) {
		$img = $this->model_file->get_info($id);
		if ($img !== FALSE) {
//			if ($img->status == 0 && $img->time > now() - 2 * 60 * 60)
				return TRUE;
		}
		$this->form_validation->set_message(__FUNCTION__, lang('invalid_image'));
		return FALSE;
	}

	public function _check_images($array) {
		if (!is_array($array)) {
			//$this->form_validation->set_message(__FUNCTION__,lang('invalid_images'));
			return TRUE;
		}
		foreach ($array as $id) {
			$img = $this->model_file->get_info($id);
			if($img!==FALSE){// && $img->status == 0 && $img->time > now() - 2 * 60 * 60){
				
			} else {
				$this->form_validation->set_message(__FUNCTION__, lang('invalid_images'));
				return FALSE;
			}
		}
		return TRUE;
	}

	public function _check_product_id($id) {
		if ($this->model_product->get_total(array('id' => $id)) == 0) {
			$this->form_validation->set_message(__FUNCTION__, lang('product_not_found'));
			return false;
		}
		return true;
	}

	public function _check_date($str) {

		$format = $this->siteConfig->date_format;
		switch ($format) {
			case 'yyyy/mm/dd':
				if (preg_match("/^(19\d\d|2\d\d\d)[\/|-](0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])$/", $str, $match) && checkdate($match[2], $match[3], $match[1])) {
					return TRUE;
				}
				break;
			case 'mm/dd/yyyy':
				if (preg_match("/^(0?[1-9]|1[012])[\/|-](0?[1-9]|[12][0-9]|3[01])[\/|-](19\d\d|2\d\d\d)$/", $str, $match) && checkdate($match[1], $match[2], $match[3])) {
					return TRUE;
				}
				break;
			default: // 'dd/mm/yyyy'
				if (preg_match("/^(0?[1-9]|[12][0-9]|3[01])[\/|-](0?[1-9]|1[012])[\/|-](19\d\d|2\d\d\d)$/", $str, $match) && checkdate($match[2], $match[1], $match[3])) {
					return TRUE;
				}
				break;
		}
		$this->form_validation->set_message(__FUNCTION__, lang('invalid_date_format'));
		return FALSE;
	}

	public function _check_location($value) {
		if (!is_array($value)) {
			$this->form_validation->set_message(__FUNCTION__, lang('location_required'));
			return false;
		}
		$this->load->model('model_location');
		foreach ($value as $location_id) {
			if ($this->model_location->get_total(array('id' => $location_id)) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_invalid_location'));
				return false;
			}
		}
		return true;
	}

	public function _check_catalogue($value) {
		if (!is_array($value)) {
			$this->form_validation->set_message(__FUNCTION__, lang('catalogue_required'));
			return false;
		}
		$this->load->model('model_catalogue');
		foreach ($value as $catalogue_id) {
			if ($this->model_catalogue->get_total(array(
				'id' => $catalogue_id,
				'type'	=> 1
				)) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_invalid_catalogue'));
				return false;
			}
		}
		return true;
	}

	public function _check_price($value) {
		if (is_numeric($value))
			if ($value >= 0)
				return true;
		$this->form_validation->set_message(__FUNCTION__, lang('price_not_valid'));
		return false;
	}

	public function _check_info($value) {
		if (!is_array($value)) {
			$this->form_validation->set_message(__FUNCTION__, lang('invalid_data'));
			return false;
		}
		foreach ($this->languages as $lang) {
			if (!isset($value[$lang->id])) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_info_invalid'));
				return false;
			} else if (!isset($value[$lang->id]['name']) || strlen($value[$lang->id]['name']) == 0) {
				$this->form_validation->set_message(__FUNCTION__, lang('product_name_required'));
				return false;
			}
		}
		return true;
	}

}

?>
